package com.epfly.promo.activity.impl;

import com.epfly.base.id.SnowflakeIdService;
import com.epfly.iface.promo.activity.ActivityEventService;
import com.epfly.iface.promo.activity.enums.ActivityRuleDinnerTypeEnum;
import com.epfly.iface.promo.activity.vo.OrderCancelEventRequest;
import com.epfly.iface.promo.activity.vo.OrderOkEventRequest;
import com.epfly.promo.activity.dao.ActivityRuleMapper;
import com.epfly.promo.activity.dao.ActivityUserRecordMapper;
import com.epfly.promo.activity.entity.ActivityRuleEntity;
import com.epfly.promo.activity.entity.ActivityUserRecordEntity;
import com.epfly.promo.activity.feign.DataRestaurantFeignService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class ActivityEventServiceImpl implements ActivityEventService {


    @Resource
    private SnowflakeIdService snowflakeIdService;

    @Resource
    private DataRestaurantFeignService dataRestaurantFeignService;

    @Resource
    private ActivityUserRecordMapper activityUserRecordMapper;

    @Resource
    private ActivityRuleMapper activityRuleMapper;

    /**
     * 待支付->支付成功的回调函数(callback)
     * 记录活动参与记录
     */
    public void orderOkEvent(OrderOkEventRequest request) {

        byte dinnerType = dataRestaurantFeignService.getMealType(request.getMerchantId(), request.getStoreId(), request.getOrderTime()).byteValue();
        ActivityRuleEntity ruleEn = activityRuleMapper.findByActivityIdAndDinnerTypeList(request.getActivityId(), Lists.newArrayList(dinnerType, ActivityRuleDinnerTypeEnum.UN_LIMIT.getKey()));

        if (Objects.nonNull(ruleEn)) {
            ActivityUserRecordEntity userRecordEntity = new ActivityUserRecordEntity();
            userRecordEntity.setId(snowflakeIdService.nextId());
            userRecordEntity.setMerchantId(request.getMerchantId());
            userRecordEntity.setStoreId(request.getStoreId());
            userRecordEntity.setActivityId(request.getActivityId());
            userRecordEntity.setRuleId(ruleEn.getId());
            userRecordEntity.setUserId(request.getUserId());
            userRecordEntity.setOrderId(request.getOrderId());
            userRecordEntity.setOrderAmount(request.getOrderAmount());
            userRecordEntity.setPayAmount(request.getPayAmount());
            userRecordEntity.setDiscountAmount(request.getDiscountAmount());
            activityUserRecordMapper.insertSelective(userRecordEntity);
        }

    }

    /**
     * 订单退款事件，清除活动参与记录
     */
    public void orderCancelEvent(OrderCancelEventRequest request) {

        activityUserRecordMapper.deleteByActivityIdAndOrderId(request.getActivityId(), request.getOrderId());
    }
}
